<template>
  <div class="v-rorm-render-form">
    <div v-for="(item, index) in fileList" :key="index" class="upload-item"  @click="handleSelectFile(index)">
      <span style="font-size: 14px">病例照片：</span>
      <el-input v-model="item.name" placeholder="未选中文件" @input="handleUploadInput" style="height: 34px">
        <template #prepend
          ><el-upload
            class="upload-box"
            action="/api/blade-resource/oss/endpoint/put-file"
            multiple
            :show-file-list="false"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :limit="500"
            :with-credentials="true"
            :headers="headers"
          >
            <el-button type="primary" @click="handleSelectFile(index)">选择文件</el-button>
          </el-upload></template
        >
      </el-input>
      <div class="action-buttons">
        <!-- 删除一项上传列表 -->
        <el-button
          type="danger"
          :icon="Minus"
          circle
          @click="removeFile(index)"
          class="action-btn"
          v-if="index != 0"
        />
        <!-- 新增一项上传列表 -->
        <el-button
          type="warning"
          :icon="Plus"
          circle
          @click="addFile"
          class="action-btn"
          v-if="index === 0"
        />
        <!-- 上传文件 -->
        <!-- <el-button type="success" :icon="Upload" @click="submitFiles" v-if="index === 0">上 传</el-button> -->
      </div>
    </div>

    <!--  element-loading-background="#f0f2f5" -->
    <div class="gather-content-right-main" v-loading="loading">
      <!-- @formChange="onFormDataChange" -->
      <VFormRender
        :form-json="formJson"
        :form-data="formData"
        :option-data="optionData"
        ref="vFormRef"
      >
      </VFormRender>
      <div style="display: flex; justify-content: center; margin-top: 10px">
        <el-button type="primary" plain :icon="Back" @click="handleGoBack">返 回</el-button>
        <el-button type="primary" plain :icon="Check" @click="handleSubmit" >提 交</el-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { Plus, Minus, Upload, Check, Back } from '@element-plus/icons-vue';

import { Base64 } from 'js-base64';
import website from '@/config/website';
import { getToken } from '@/utils/auth';

import { eleMedicalRecordSubmit,eleMedicalRecordDetail } from '@/api/casemanagement/caseManagement';
import { getDetail } from '@/api/crf/crf.js';
import VFormRender from '@/components/form-render/index.vue';
import { sendVRormRenderFormJson } from './VRormRenderFormJson';
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const router = useRouter();
const store = useStore();
const route = useRoute();
const routerQuery = ref({});
routerQuery.value = route.query;
const formJson = ref({});
const vFormRef = ref(null);
const formData = ref({});
const optionData = ref({});
let uploadInput = ref('');
const headers = ref({
  Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`,
  'Blade-Requested-With': 'BladeHttpRequest',
});
let loading = ref(true)

// 文件列表数据
const fileList = ref([
  { link: null, name: '', classification: '1', caseId: routerQuery.value.caseManagementId },
]);
// 文件列表长度
const fileListLength = ref(0);

onMounted(() => {
  initVFormData();
});
// 问卷表单回显
/* 
  routerVal.eleMedicalRecordType 1：诊断点击进入
  routerVal.eleMedicalRecordType 2：医嘱点击进入
  routerVal.eleMedicalRecordType 3：添加病例点击进入
  routerVal.eleMedicalRecordType 12：列表病例名称点击进入
*/
const initVFormData = () => {
  let sendFormJson = {};
  let routerVal = route.query;
  if (routerVal.eleMedicalRecordType === '1' || routerVal.eleMedicalRecordType === '2') {
    if (routerVal.eleMedicalRecordName === '首次诊断') {
      sendFormJson = sendVRormRenderFormJson.addCase1;
    } else if (routerVal.eleMedicalRecordName === '复诊') {
      sendFormJson = sendVRormRenderFormJson.addCase2;
    } else {
      sendFormJson = sendVRormRenderFormJson.adviceTable;
    }
    formJson.value = sendFormJson;
    vFormRef.value.setFormJson(formJson.value);
    loading.value = false;
  } else if (routerVal.eleMedicalRecordType === '3' && routerVal.crfId) {
    getDetailData(routerVal.crfId);
  }
  else if(routerVal.eleMedicalRecordType === '12' && routerVal.eleMedicalRecordId){
    getEleMedicalRecordDetail(routerVal.eleMedicalRecordId);
  }
};
// 通过crfId获取问卷内容
const getDetailData = async crfId => {
  const { data: res } = await getDetail(crfId);
  if (res.code == 200) {
    formJson.value = JSON.parse(res.data.content);
    vFormRef.value.setFormJson(formJson.value);
    loading.value = false;
  }
};
// 通过电子病例ID获取问卷内容以及问卷填写详情
const getEleMedicalRecordDetail = async (eleMedicalRecordId) => {
  const { data: res } = await eleMedicalRecordDetail(eleMedicalRecordId);
  if (res.code == 200) {
    if(res.data.content){
      formData.value = JSON.parse(res.data.content);
    }
    console.log(formData.value);
    setTimeout(() => {
      formJson.value = JSON.parse(res.data.question);
      vFormRef.value.setFormJson(formJson.value);
    },0)
    if(res.data.informationList.length != 0){
      fileList.value = res.data.informationList;
    }
  }
  loading.value = false;
};

// 添加文件项
const addFile = () => {
  fileList.value.push({
    link: null,
    name: '',
    classification: '1',
    caseId: routerQuery.value.caseManagementId,
  });
};

// 删除文件项
const removeFile = index => {
  if (fileList.value.length > 1) {
    fileList.value.splice(index, 1);
  }
};
// 选择文件按钮点击
const handleSelectFile = index => {
  fileListLength.value = index;
};
// 选择文件输入框input事件
const handleUploadInput = e => {
  if(e === ''){
    console.log(e,fileListLength.value);
    fileList.value[fileListLength.value].link = "";
    fileList.value[fileListLength.value].name = "";
  }
};
// 上传图片之前钩子
const beforeUpload = () => {
  headers.value[website.tokenHeader] = 'bearer ' + getToken();
};
// 上传成功钩子
const handleSuccess = (response, file, fileLists) => {
  console.log('上传成功', response.data, fileListLength.value, fileList.value);
  // uploadInput.value = fileList.map(ele => ele.name).join(',');
  fileList.value[fileListLength.value].name = response.data.originalName;
  fileList.value[fileListLength.value].link = response.data.link;
};

// 提交按钮点击事件
const handleSubmit = () => {
  vFormRef.value.getFormData().then(res => {
    let form = {
      name: routerQuery.value.eleMedicalRecordName,
      caseId: routerQuery.value.caseManagementId,
      question: JSON.stringify(formJson.value),
      content: JSON.stringify(res),
      informationList: fileList.value,
      remark: routerQuery.value.eleMedicalRecordRemark ? routerQuery.value.eleMedicalRecordRemark : routerQuery.value.eleMedicalRecordName,
      id: routerQuery.value.eleMedicalRecordId || null,
    };
    console.log('表单数据', res, fileList.value, form);
    eleMedicalRecordSubmit(form).then(res => {
      ElMessage.success('提交成功!');
      setTimeout(() => {
        handleGoBack();
      }, 1000);
    });
  });
};
// 返回按钮点击
const handleGoBack = () => {
  routerQuery.value.selectTab = '2';
  delete routerQuery.value.eleMedicalRecordName;
  delete routerQuery.value.eleMedicalRecordType;
  delete routerQuery.value.eleMedicalRecordRemark;
  delete routerQuery.value.crfId;
  delete routerQuery.value.eleMedicalRecordId;
  router.replace({
    path: '/casemanagement/tabs',
    query: {
      ...routerQuery.value,
    },
  });
};

// 提交文件
const submitFiles = () => {
  const files = fileList.value.map(item => item.link).filter(file => file !== null);

  // 这里调用你的后端接口
  console.log('待上传文件数组:', files);
};
</script>
<style scoped lang="scss">
.v-rorm-render-form {
  width: 90%;
  height: 95%;
  margin: 0 5%;
  padding: 15px;
}
.upload-container {
  width: 600px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
}

.upload-item {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 15px 0;
  gap: 10px;
  ::v-deep .el-input-group {
    width: 500px;
  }
}

.upload-box {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-name {
  color: #666;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.action-btn {
  width: 36px;
  height: 36px;
}
.gather-content-right-main {
  padding: 20px 0;
  border-top: 1px solid #d9dcde;
}
</style>